package com.bjy.qa.agent.tester.handlers;

import com.alibaba.fastjson.JSONObject;
import com.bjy.qa.agent.enumtype.ConditionEnum;
import com.bjy.qa.agent.enumtype.RunStatus;
import com.bjy.qa.agent.model.HandleDes;
import com.bjy.qa.agent.tester.RunStepThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * while 步骤
 */
@Component
public class WhileHandler implements StepHandler {
    @Autowired
    private NoneConditionHandler noneConditionHandler;
    @Autowired
    private StepHandlers stepHandlers;

    /**
     * while 步骤
     * @param stepJSON 步骤 json
     * @param handleDes HandleDes 模型
     * @param thread RunStepThread
     * @return
     * @throws Throwable
     */
    @Override
    public HandleDes runStep(JSONObject stepJSON, HandleDes handleDes, RunStepThread thread) throws Throwable {
        if (thread.isStopped()) {
            return null;
        }
        handleDes.clear();

        // 取出 while 下的步骤集合
        JSONObject conditionStep = stepJSON.getJSONObject("step");
        List<JSONObject> steps = conditionStep.getJSONArray("childSteps").toJavaList(JSONObject.class);

        String stepDesc = conditionStep.getString("desc"); // 步骤描述

        // 设置了判断条件步骤，则先运行判断条件的步骤
        thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "开始执行「while」步骤", "");
        noneConditionHandler.runStep(stepJSON, handleDes, thread);
        int i = 1;
        while(handleDes.getE() == null && !thread.isStopped()) {
            // 条件步骤成功，取出while下所属的步骤丢给stepHandlers处理
            thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "「while」步骤通过，开始执行第「" + i + "」次子步骤循环", "");
            for (JSONObject step : steps) {
                stepHandlers.runStep(handlerPublicStep(step), handleDes, thread);
            }
            thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "第「" + i + "」次子步骤执行完毕", "");

            handleDes.clear();
            thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "开始执行第「" + (i+1) + "」次「while」步骤", "");
            noneConditionHandler.runStep(stepJSON, handleDes, thread);

            i++;
        }
        if (handleDes.getE() != null) {
            thread.getLogTool().sendStepLog(RunStatus.WARN, stepDesc, "「while」步骤执行失败，循环结束", "");
        }
        if (thread.isStopped()) {
            thread.getLogTool().sendStepLog(RunStatus.WARN, stepDesc, "「while」被强制中断", "");
        }
        // 不满足条件则返回
        return handleDes;
    }

    /**
     * 获取步骤类型
     * @return
     */
    @Override
    public ConditionEnum getCondition() {
        return ConditionEnum.WHILE;
    }
}
